package hxy.dragon.qrcode

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeContentPadding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.datetime.Clock
import org.jetbrains.compose.ui.tooling.preview.Preview
import qrcode.QRCode

@Composable
@Preview
fun App() {
    MaterialTheme {
        var showContent by remember { mutableStateOf(false) }
        var qrCodeImage by remember { mutableStateOf<ImageBitmap?>(null) }
        var currentTimestamp by remember { mutableStateOf<String?>(null) }

        Column(
            modifier = Modifier
                .background(MaterialTheme.colorScheme.primaryContainer)
                .safeContentPadding()
                .fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            Button(onClick = {
                showContent = !showContent
                // 当显示内容时，生成当前时间戳的二维码
                if (showContent) {
                    // 在后台线程生成二维码
                    generateQRCode { imageBitmap, timestamp ->
                        qrCodeImage = imageBitmap
                        currentTimestamp = timestamp
                    }
                } else {
                    qrCodeImage = null
                    currentTimestamp = null
                }
            }) {
                Text("点击生成时间戳二维码")
            }
            AnimatedVisibility(showContent) {
                val greeting = remember { Greeting().greet() }
                Column(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally,
                ) {
                    qrCodeImage?.let { imageBitmap ->
                        Image(
                            bitmap = imageBitmap,
                            contentDescription = "Unix时间戳二维码",
                            modifier = Modifier.fillMaxSize(0.7f)
                        )
                    } ?: run {
                        Text("正在生成二维码...")
                    }
                    currentTimestamp?.let { timestamp ->
                        Text(
                            text = "会员码: $timestamp",
                            style = MaterialTheme.typography.bodyMedium,
                            modifier = Modifier.padding(vertical = 8.dp)
                        )
                    }
                    Text("超级会员：2026-09-07到期")
                }
            }
        }
    }
}

// 生成二维码的函数
fun generateQRCode(onResult: (ImageBitmap?, String?) -> Unit) {
    CoroutineScope(Dispatchers.Main).launch {
        try {
            val (imageBitmap, timestamp) = withContext(Dispatchers.Default) {
                val unixTime = Clock.System.now().toEpochMilliseconds()
                val timestamp = "1964564835178762242_${unixTime}"
                val qrCode = QRCode(timestamp)
                // 生成二维码图像并转换为 Compose ImageBitmap
                val imageBytes = qrCode.renderToBytes()
                val imageBitmap = bytesToImageBitmap(imageBytes)
                Pair(imageBitmap, timestamp)
            }
            onResult(imageBitmap, timestamp)
        } catch (e: Exception) {
            e.printStackTrace()
            onResult(null, null)
        }
    }
}

// 平台特定的字节数组转ImageBitmap函数
expect fun bytesToImageBitmap(bytes: ByteArray): ImageBitmap?